package com.qf.shiro;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;

import java.util.Scanner;

/**
 * projectName: 2103--RBAC
 *
 * @author: MaTianWei
 * time: 2021/7/9 11:24
 * description:
 */

public class AuthorizationDemo {
    public static void main(String[] args) {

        //1·创建securityManagerFactory
        IniSecurityManagerFactory factory = new IniSecurityManagerFactory("classpath:shiro.ini");
        //2·创建securityManager
        SecurityManager securityManager = factory.getInstance();
        //3·引出securityManagerUtil 放入全局变量
        SecurityUtils.setSecurityManager(securityManager);
        //4·获取subject
        Subject subject = SecurityUtils.getSubject();
        //5·认证
        Scanner scanner = new Scanner(System.in);
        System.out.println("输入你的账号");
        String account = scanner.nextLine();
        System.out.println("输入你的密码");
        String password = scanner.nextLine();

        UsernamePasswordToken token = new UsernamePasswordToken(account, password);

        try {
            boolean authenticated = subject.isAuthenticated();
            System.out.println("认证前:authenticated = " + authenticated);
            //只有认证通过才可以获取对应的账号信息!
            //获取用户数据 放入session
            Object principal = subject.getPrincipal();
            System.out.println("principal = " + principal);
            //6.授权
            //检查有没有角色
            boolean is = subject.hasRole("teacher"); //boolean
            System.out.println("是否有讲师角色 = " + is);
            //subject.checkRole(); // void
            //检查有没有权限
            boolean anpai = subject.isPermitted("anpai");
            System.out.println("anpai = " + anpai);
            //subject.checkPermission();
            subject.login(token);
            System.out.println("认证成功");
        } catch (AuthenticationException e) {
            System.out.println("认证失败!");
        }
        boolean authenticated = subject.isAuthenticated();
        System.out.println("认证后:authenticated = " + authenticated);
        //7.取消认证
        subject.logout();
    }

}